package internal;

import java.util.concurrent.Executor;

/** 因为底层是使用 Runnable,会自己关闭线程
 *  事件的具体实现
 * Created by DJJ on 2019/3/28.
 */
public class MyEventBus implements Bus {

    private final MyRegistry myRegistry=new MyRegistry();

    private String busName;

    private final static String DEFAULT_BUS_NAME="default";

    private final static String DEFAULT_TOPIC = "default-topic";

    private final MyDispatcher myDispatcher;

    public MyEventBus()
    {
        this(DEFAULT_BUS_NAME, null, MyDispatcher.SEQ_EXECUTOR_SERVICE);
    }

    public MyEventBus(String busName)
    {
        this(busName, null, MyDispatcher.SEQ_EXECUTOR_SERVICE);
    }

    MyEventBus(String busName, MyEventExceptionHandler exceptionHandler, Executor executor){
        this.busName=busName;
        this.myDispatcher= MyDispatcher.newDispatcher(exceptionHandler,executor);
    }
    public MyEventBus(MyEventExceptionHandler exceptionHandler)
    {
        this(DEFAULT_BUS_NAME, exceptionHandler, MyDispatcher.SEQ_EXECUTOR_SERVICE);
    }
    @Override
    public void register(Object subscriber) {
        myRegistry.bind(subscriber);
    }

    @Override
    public void unregister(Object subscriber) {
        myRegistry.unbind(subscriber);
    }

    @Override
    public void post(Object event) {
        myDispatcher.dispatch(this,myRegistry,event,DEFAULT_TOPIC);
    }

    @Override
    public void post(Object event, String topic) {
        myDispatcher.dispatch(this,myRegistry,event,topic);
    }

    @Override
    public void close() {
        try {
            myDispatcher.close();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getBusName() {
        return null;
    }
}
